package org.easy.rocketmq.producer.controller;

import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.TransactionMQProducer;
import org.apache.rocketmq.common.message.Message;
import org.easy.rocketmq.producer.configure.TestTransactionListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import lombok.extern.log4j.Log4j2;

@RestController
@RequestMapping("/test")
@Log4j2
public class TestController {

    @Autowired
    private DefaultMQProducer defaultProducer;

    @Autowired
    private TransactionMQProducer transactionMQProducer;

    @Autowired
    private TestTransactionListener testTransactionListener;

    static int count = 0;

    @GetMapping("/test")
    public void test(String info) throws Exception {

        System.out.println("进入 controller .....");
        // 主题
        // tag
        // key
        //
        Message message = new Message("t_Topic_easy", "mumu", "12345", ("rocketmq测试[" + info + "]" + count).getBytes());
        // 这里用到了这个mq的异步处理，类似ajax，可以得到发送到mq的情况，并做相应的处理
        // 不过要注意的是这个是异步的

        // SendResult sendResult = defaultProducer.send(message);
        // log.info("传输成功" + sendResult);

        transactionMQProducer.send(message, new SendCallback() {

            @Override
            public void onSuccess(SendResult sendResult) {
                log.info("传输成功" + sendResult);
            }

            @Override
            public void onException(Throwable e) {
                log.error("传输失败", e);
            }
        });

    }
}
